import $http from '@/config/requestHttp.js'
/**
 * 工具函数
 * form:
 * 		首单：order
 * 		充值：recharge
 * 		加钟：clock
 * 		升级：upgrade
 */

// 创建订单
const createOrder = async (params) => {
    const res = await $http.post('api/recharge/createOrder', params)
    return res
}

// pay pay


// 跳转小程序 
// api/wxapp/get_jump_link
export const miniProgram = async (sn) => {
    console.log('this.$http.post', $http.post);
    const res = await $http.post('api/wxapp/get_jump_link', {order_sn: sn})
}

// 轮询监听支付状态
const checkOrderStatus = (order_sn, form) => {
	console.log('order_sn', order_sn);
	const time =  setInterval(async () => {
		const res = await $http.post('api/wxapp/check_order_status', {order_sn, form})
		console.log('checkOrderStatus==>', res);
	}, 1000)
}

// 发起支付
export const payOrder = async (params) => {
    console.log(params);
	
	checkOrderStatus(params.order_sn, params.form)
	
	$http.post('api/pay/pay', params)
	.then(res => {
		console.log('pay=>res', res);
		// res.url_link
		plus.runtime.openURL(res.url_link);
	}).catch(err=>{
		// uni.hideLoading()
	})
}


// 余额 充值
export const blanceRecharge = async (params) => {
    // 1. 创建订单
    const order_sn = await  createOrder(params)
    // 2. 跳转小程序
	$http.post("api/pay/pay", { order_sn, pay_way: 4, form: 'recharge' })
        .then((res) => {
		  console.log('pay=>res', res);
          plus.runtime.openURL(res.url_link);
		  
		  // 3.监听订单状态
		  checkOrderStatus(order_sn, 'recharge')
		});
}


// 余额 支付
export const blancePay = (params) => {
	$http.post('api/pay/pay', params)
	.then(res => {
		uni.hideLoading()
		uni.redirectTo({
			url: '/bundle/pages/pay_success/pay_success'
		});
	}).catch(err=>{
		uni.hideLoading()
	})
}